package com.xinjiang.electricpower.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.utils.PageUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.uuid.UUID;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.system.api.domain.SysUser;
import com.xinjiang.electricpower.domain.DTO.PsmWorkOrderDTO;
import com.xinjiang.electricpower.domain.DTO.VoucherDTO;
import com.xinjiang.electricpower.domain.PsmWorkOrder;
import com.xinjiang.electricpower.domain.TgManageUser;
import com.xinjiang.electricpower.domain.vo.AuthInfoVo;
import com.xinjiang.electricpower.domain.vo.PsmWorkOrderDetailVO;
import com.xinjiang.electricpower.domain.vo.PsmWorkOrderVO;
import com.xinjiang.electricpower.enums.ElectricPowerEnums;
import com.xinjiang.electricpower.mapper.PsmWorkOrderMapper;
import com.xinjiang.electricpower.service.IPsmWorkOrderService;
import com.xinjiang.electricpower.service.ITgManageUserService;
import com.xinjiang.electricpower.service.IUserAuthService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author feizhao
 * @date 2022/11/9
 * @apiNote 派工单服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class PsmWorkOrderServiceImpl extends ServiceImpl<PsmWorkOrderMapper, PsmWorkOrder> implements IPsmWorkOrderService {

    private final TokenService tokenService;
    private final ITgManageUserService tgManageUserService;
    private final IUserAuthService userAuthService;

    public PageInfo<PsmWorkOrderVO> selectPsmWorkOrdersPage(PageDTO<PsmWorkOrderVO> page, PsmWorkOrderDTO psmWorkOrderDTO) {
        QueryWrapper<PsmWorkOrderVO> wrapper = getPsmWorkOrderVOQueryWrapper(psmWorkOrderDTO);
        //开启分页功能
        List<PsmWorkOrder> psmWorkOrders = baseMapper.findPsmWorkOrders(wrapper);
        //封装数据
        List<PsmWorkOrderVO> psmWorkOrderVOs = this.getPsmWorkOrderVOS(psmWorkOrders);
        return PageUtils.getFormDataPageInfo(Integer.parseInt(String.valueOf(page.getCurrent())), Integer.parseInt(String.valueOf(page.getSize())), psmWorkOrderVOs);
    }

    @NotNull
    private List<PsmWorkOrderVO> getPsmWorkOrderVOS(List<PsmWorkOrder> psmWorkOrders) {
        List<PsmWorkOrderVO> psmWorkOrderVOs = new ArrayList<>();
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        psmWorkOrders.forEach(psmWorkOrder -> {
            LocalDateTime parse = null;
            if (ObjectUtils.isNotEmpty(psmWorkOrder.getCreateTime())) {
                parse = LocalDateTime.parse(psmWorkOrder.getCreateTime(), fmt);
            }
//            String[] split = null;
//            if (ObjectUtils.isNotEmpty(psmWorkOrder.getBusinessType())) {
//                split = psmWorkOrder.getBusinessType().split(",");
//            }
            //装填数据
            psmWorkOrderVOs.add(PsmWorkOrderVO.builder().id(psmWorkOrder.getId()).createTime(parse)
                    .workNo(psmWorkOrder.getWorkNo()).workName(psmWorkOrder.getWorkName()).businessType(psmWorkOrder.getBusinessType())
                    .responsible(psmWorkOrder.getResponsible()).createUser(psmWorkOrder.getCreateUser()).approveUser(psmWorkOrder.getApproveUser())
                    .status(psmWorkOrder.getStatus()).build());
        });
        return psmWorkOrderVOs;
    }

    @NotNull
    private QueryWrapper<PsmWorkOrderVO> getPsmWorkOrderVOQueryWrapper(PsmWorkOrderDTO psmWorkOrderDTO) {
        AuthInfoVo authStr = userAuthService.getAuthStr();
        QueryWrapper<PsmWorkOrderVO> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotEmpty(authStr.getOrgNo()),"ORGID",authStr.getOrgNo());
        wrapper.in(ObjectUtils.isNotEmpty(authStr.getConsNo()),"RESPONSIBLE",authStr.getConsNo());
        wrapper.like(StringUtils.hasText(psmWorkOrderDTO.getWorkNo()), "pwo.work_no", psmWorkOrderDTO.getWorkNo());
        wrapper.like(StringUtils.hasText(psmWorkOrderDTO.getWorkName()), "pwo.work_name", psmWorkOrderDTO.getWorkName());
        wrapper.eq(StringUtils.hasText(psmWorkOrderDTO.getStatus()), "pwo.status", psmWorkOrderDTO.getStatus());
        wrapper.eq(StringUtils.hasText(psmWorkOrderDTO.getBusinessType()), "pwo.business_type", psmWorkOrderDTO.getBusinessType());
        wrapper.ge(ObjectUtils.isNotEmpty(psmWorkOrderDTO.getCreateTimeBegin()), "CONVERT(pwo.create_time, date)", psmWorkOrderDTO.getCreateTimeBegin());
        wrapper.le(ObjectUtils.isNotEmpty(psmWorkOrderDTO.getCreateTimeEnd()), "CONVERT(pwo.create_time, date)", psmWorkOrderDTO.getCreateTimeEnd());
        wrapper.eq(StringUtils.hasText(psmWorkOrderDTO.getResponsible()), "pwo.responsible", psmWorkOrderDTO.getResponsible());
        wrapper.orderByDesc("pwo.create_time");
        return wrapper;
    }

    /**
     * 查询总数
     *
     * @return Long
     */
    @Override
    public Long countDispatchWorkOrder() {
        AuthInfoVo authStr = userAuthService.getAuthStr();
        QueryWrapper<PsmWorkOrder> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotEmpty(authStr.getOrgNo()),"ORGID",authStr.getOrgNo());
        wrapper.in(ObjectUtils.isNotEmpty(authStr.getConsNo()),"RESPONSIBLE",authStr.getConsNo());
        return super.count(wrapper);
    }

    /**
     * 查询派工单列表无分页
     *
     * @param psmWorkOrderDTO 派工单DTO类
     * @return List<PsmWorkOrderVO> 返回派工单列表
     */
    @Override
    public List<PsmWorkOrderVO> selectPsmWorkOrders(PsmWorkOrderDTO psmWorkOrderDTO) {
        return this.getPsmWorkOrderVOS(baseMapper.findPsmWorkOrders(this.getPsmWorkOrderVOQueryWrapper(psmWorkOrderDTO)));
    }

    /**
     * 查询工单列表无分页
     *
     * @param ids 批量id
     * @return List<PsmWorkOrderVO> 返回派工单列表
     */
    @Override
    public List<PsmWorkOrderVO> selectPsmWorkOrders(String... ids) {
        QueryWrapper<PsmWorkOrderVO> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", Arrays.asList(ids));
        return this.getPsmWorkOrderVOS(baseMapper.findPsmWorkOrders(queryWrapper));
    }

    /**
     * 删除派工单
     *
     * @param id id
     * @return Long 受影响的行数
     */
    @Override
    public boolean removePsmWorkOrders(String id) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("status", ElectricPowerEnums.PSM_WORK_ORDER_STATUS_ISSUE.getValue());
        return super.removeByMap(map);
    }

    /**
     * 查看详情
     *
     * @param id 派工单id
     * @return PsmWorkOrderDetailVO 派工单详情VO类
     */
    @Override
    public PsmWorkOrderDetailVO selectPsmWorkOrderDetail(String id) {
        PsmWorkOrder psmWorkOrder = super.getById(id);
        LambdaQueryWrapper<TgManageUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TgManageUser::getTgId, StringUtils.isNotEmpty(psmWorkOrder.getAreaId()) ? psmWorkOrder.getAreaId() : null);
        TgManageUser tg = tgManageUserService.getOne(queryWrapper);
        if (ObjectUtils.isNotEmpty(psmWorkOrder)) {
            PsmWorkOrderDetailVO psmWorkOrderDetailVO = new PsmWorkOrderDetailVO();
            if (ObjectUtils.isNotEmpty(tg)) {
                psmWorkOrderDetailVO.setTgName(tg.getTgName());
            }
            BeanUtils.copyProperties(psmWorkOrder, psmWorkOrderDetailVO);
            if (StringUtils.isNotEmpty(psmWorkOrder.getBusinessType())) {
                psmWorkOrderDetailVO.setBusinessTypeArray(psmWorkOrder.getBusinessType());
            }
            if (StringUtils.isNotEmpty(psmWorkOrder.getMembers())) {
                psmWorkOrderDetailVO.setMembers(psmWorkOrder.getMembers().split(","));
            }
            return psmWorkOrderDetailVO;
        }
        return null;
    }

    /**
     * 制单
     *
     * @param voucherDTO 派工单-制单VO
     * @return int 返回成功与否
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertPsmWorkOrder(VoucherDTO voucherDTO) {
        SysUser sysUser = tokenService.getLoginUser().getSysUser();
        PsmWorkOrder psmWorkOrder = new PsmWorkOrder();
        //TODO 制单人设置值
        psmWorkOrder.setCreateUser(sysUser.getUserName());
        psmWorkOrder.setWorkNo(UUID.randomUUID().toString().replaceAll("-", ""));
        BeanUtils.copyProperties(voucherDTO, psmWorkOrder);
        return super.save(psmWorkOrder);
    }

    /**
     * 制单
     *
     * @param voucherDTO 派工单-结单VO
     * @return int 返回成功与否
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updatePsmWorkOrder(VoucherDTO voucherDTO) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        PsmWorkOrder psmWorkOrder = new PsmWorkOrder();
        if (StringUtils.isNotEmpty(voucherDTO.getStatus())) {
            if (voucherDTO.getStatus().equals(ElectricPowerEnums.PSM_WORK_ORDER_STATUS_ISSUED.getValue())) {
                SysUser sysUser = tokenService.getLoginUser().getSysUser();
//                psmWorkOrder.setApproveUser(SecurityUtils.getLoginUser().getUsername());
                psmWorkOrder.setApproveUser(sysUser.getUserName());
                psmWorkOrder.setApproveTime(LocalDateTime.now().format(dateTimeFormatter));
            }
        }
        BeanUtils.copyProperties(voucherDTO, psmWorkOrder);
        return super.updateById(psmWorkOrder);
    }
}
